package com.iot.beidou;

/**
 * @author Cao.ning
 * @date 2023/2/28
 */
import com.iot.beidou.dto.SerialPortMsg;
import gnu.io.SerialPort;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;

@Service
public class BeiDouDevice {
    private static final Logger logger = LoggerFactory.getLogger(BeiDouDevice.class);
    //SerialPortMsg serialPortMsg = new SerialPortMsg();
    /**
     * 如果不需要接入北斗设备，这个@PostConstruct注解可以直接注释掉，这样就不会运行北斗相关的数据连接了，不再去连接串口
     */
    @PostConstruct
    public void start(){
        if(System.getProperty("os.name").indexOf("Windows")>-1) {
            //查看所有串口
            SerialPortUtil serialPortUtil = SerialPortUtil.getSerialPortUtil();
            ArrayList<String> ports = serialPortUtil.findPort();
            logger.info("发现全部串口：" + ports);
            for(String port : ports){
                this.init(port);
            }
        }
    }

    public void init(String portName)
    {
        SerialPortUtil serialPortUtil = SerialPortUtil.getSerialPortUtil();
        //打开该对应portName名字的串口
        SerialPort serialPort = serialPortUtil.openPort(
                portName,
                9600,
                SerialPort.DATABITS_8,
                SerialPort.PARITY_NONE,
                SerialPort.PARITY_ODD);
        if(serialPort != null){
            SerialPortMsg.serialPort=serialPort;
            serialPortUtil.addListener(serialPort, new BeiDouDevicePortLister(serialPort));
        }
    }

}